//
//  CECaptialSettingCell.m
//  digitalCurrency
//
//  Created by 默认账户 on 2019/4/3.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CECaptialResettingVC.h"
#import "CESettingsCell.h"
#import "MineNetManager.h"
//#import "ShowLoGinVC.h"
#import "MSVerifyCell.h"
#import "CustomButton.h"

@interface CECaptialResettingVC ()

@property (nonatomic, copy) NSArray *titles;
@property (nonatomic, strong) UIButton *besureBtn;
@property (nonatomic, strong) UITextField *moneyPassword;
@property (nonatomic, strong) UITextField *certainPassword;
@property (nonatomic, strong) UITextField *verifyCode;

@end

@implementation CECaptialResettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.viewTitle.text = LocalizationKey(@"Change asset password");
    
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 240);
    self.tableView.rowHeight = 65;
    self.tableView.separatorColor = [UIColor whiteColor];

    [self.tableView registerClass:[CESettingsCell class] forCellReuseIdentifier:@"setcell"];
    [self.tableView registerClass:[MSVerifyCell class] forCellReuseIdentifier:@"verifyCell"];
    
    _titles = @[LocalizationKey(@"Please enter verification code"),LocalizationKey(@"Please enter new password"),LocalizationKey(@"Please enter new password again")];
    
    [self.view addSubview:self.besureBtn];
    
    @weakify(self);
    [[self.besureBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self changeMoneyPassword];
    }];
}


- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
}
    
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row) {
        CESettingsCell *cell = [CESettingsCell createTableView:tableView];
        cell.placeHolder = _titles[indexPath.row];
        switch (indexPath.row) {
            case 1:
                self.moneyPassword = cell.textField;
                break;
            case 2:
                self.certainPassword = cell.textField;
                break;
            default:
                break;
        }
        return cell;
    }
    else {
        MSVerifyCell *cell  = [MSVerifyCell createTableView:tableView];
        self.verifyCode     = cell.textField;
        
        [[cell.verifyBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self codeBtnClick:cell.verifyBtn];
        }];
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
}
    
//MARK:--获取验证码的点击事件
- (void)codeBtnClick:(UIButton *)sender {
    [MineNetManager resetMoneyPasswordCodeForCompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        NSInteger codeint = [resPonseObj[@"code"] integerValue];
        if (code) {
            if (codeint == 0) {
                [self.view makeToast:LocalizationKey(@"getMessageCodeTip") duration:1.5 position:CSToastPositionCenter];
                __block int timeout=60; //倒计时时间
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(_timer, ^{
                    if(timeout<=0){ //倒计时结束，关闭
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle:LocalizationKey(@"getVerifyCode") forState:UIControlStateNormal];
                            sender.userInteractionEnabled = YES;
                        });
                    }
                    else {
                        int seconds = timeout % 90;
                        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle: [NSString stringWithFormat:@"%@s",strTime] forState:UIControlStateNormal];
                            sender.userInteractionEnabled = NO;
                        });
                        timeout--;
                    }
                });
                dispatch_resume(_timer);
            }
            else if (codeint == -1000001 ){
                [self showLoginViewController];
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}


//MARK:--修改资金密码的接口
-(void)changeMoneyPassword {
    NSString *moneyPassword   = self.moneyPassword.text;
    NSString *certainPassword = self.certainPassword.text;
    NSString *verifyCode      = self.verifyCode.text;

    if ([NSString stringIsNull:verifyCode]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputCode" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([NSString stringIsNull:moneyPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputNewMoneyPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([NSString stringIsNull:certainPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"inputCertainMoneyPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if (![certainPassword isEqualToString:moneyPassword]) {
        [self.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"checkPassword" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if (![ToolUtil matchPassword:moneyPassword]) {
        [self.view makeToast:LocalizationKey(@"Enter a password combining 8-20 digits and letters") duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    [MineNetManager resetMoneyPasswordForCode:verifyCode withNewPassword:moneyPassword CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        NSInteger codeint = [resPonseObj[@"code"] integerValue];
        if (code) {
            if (codeint == 0) {
                //上传成功
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.0 position:CSToastPositionCenter];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            else if (codeint == -1000001){
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else{
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
            
        }
    }];
}

- (UIButton *)besureBtn {
    if (!_besureBtn) {
        _besureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _besureBtn.layer.cornerRadius = 4;
        [_besureBtn setTitle:LocalizationKey(@"Confirm") forState:UIControlStateNormal];
        [_besureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _besureBtn.backgroundColor = [UIColor colorWithHEX:maincolor];
        _besureBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _besureBtn.frame = CGRectMake(23, 240, SCREEN_WIDTH-46, 40);
    }
    
    return _besureBtn;
}

@end
